<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :schemas="schemas" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, toRefs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { formSchema } from './tableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    props: {
      type: {
        type: String,
        default: () => {
          return 'add';
        },
      },
      powerInfoList: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      console.log(BasicTree);
      const isUpdate = ref(true);
      const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
      const data: any = reactive({
        type: 'add',
        schemas: formSchema,
        treeData: [],
        replaceFields: {
          children: 'children',
          title: 'name',
          key: 'id',
        },
        checkedKeys: [],
        powerList: [],
      });

      const [registerForm, { resetFields, setFieldsValue, resetSchema, setProps, validate }] =
        useForm({
          labelWidth: 100,
          schemas: formSchema,
          showActionButtonGroup: false,
          baseColProps: { lg: 12, md: 24 },
          fieldMapToTime: [['datetime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
        });
      const formId = ref(null);
      const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formId.value = props.type === 'edit' ? data.record.id : null;

        setProps({
          mergeDynamicData: { propsType: props.type },
        });
        console.log('我是查看数据：', props, data.record, isUpdate.value);
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          if (!data.record.formName) {
            setFieldsValue({
              formId: null,
            });
          }
        }
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          let params = { ...values };
          if (formId.value) {
            params.id = formId.value;
          }
          emit('success', params);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        ...toRefs(data),
        asyncExpandTreeRef,
      };
    },
  });
</script>
